<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';

// 基础URL
const baseUrl = 'http://localhost:8000';

// 状态变量
const doctorList = ref([]);
const rolesList = ref([]);
const resourcesList = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);
const dialogTitle = ref('添加医生');
const isEdit = ref(false);


// 搜索条件
const searchForm = reactive({
  name: '',
  department: '',
});

// 当前选中的医生ID
const currentDoctorId = ref(null);

// 表单数据
const formData = reactive({
  name: '',
  phone: '',
  role_id: '',
  department_id: '',
  resources: []
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入医生姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  role_id: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  department_id: [
    { required: true, message: '请选择科室', trigger: 'change' }
  ]
};

const formRef = ref(null);



// 获取请求头
const getHeaders = () => {
  const token = localStorage.getItem('token');
  return {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  };
};

// 获取医生列表
const getDoctorList = async () => {
  loading.value = true;
  try {
    const response = await axios.get(`${baseUrl}/manage/doctor-permission/`, {
      headers: getHeaders()
    });
    
    console.log('医生列表数据:', response.data);
    
    // 检查第一个医生的完整数据
    if (response.data && response.data.data && response.data.data.length > 0) {
      console.log('第一个医生的完整数据:', response.data.data[0]);
    }
    
    let doctors = [];
    
    if (response.data && response.data.code === 200 && response.data.data) {
      doctors = response.data.data;
    } else if (response.data && Array.isArray(response.data)) {
      doctors = response.data;
    } else {
      ElMessage.warning('获取医生列表数据格式异常');
      console.error('数据格式异常:', response.data);
      loading.value = false;
      return;
    }
    
    // 处理每个医生的科室和角色信息
    doctors.forEach(doctor => {
      // 确保resources字段存在且为数组
      if (!doctor.resources) {
        doctor.resources = [];
      } else if (!Array.isArray(doctor.resources)) {
        // 如果resources不是数组，尝试解析或转换
        try {
          if (typeof doctor.resources === 'string') {
            doctor.resources = JSON.parse(doctor.resources);
          } else {
            doctor.resources = [];
          }
        } catch (e) {
          doctor.resources = [];
        }
      }
      
      // 确保角色和科室字段存在
      if (!doctor.role_name && doctor.role) {
        const role = rolesList.value.find(r => r.id === Number(doctor.role));
        if (role) {
          doctor.role_name = role.name;
        }
      }
      
      if (!doctor.department_name && doctor.department) {
        const department = departmentList.value.find(d => d.id === Number(doctor.department));
        if (department) {
          doctor.department_name = department.name;
        }
      }
    });
    
    doctorList.value = doctors;
    console.log('处理后的医生列表:', doctorList.value);
  } catch (error) {
    console.error('获取医生列表失败:', error);
    ElMessage.error('获取医生列表失败，请检查网络连接或权限');
  } finally {
    loading.value = false;
  }
};

// 获取角色列表
const getRolesList = async () => {
  try {
    const response = await axios.get(`${baseUrl}/manage/roles/`, {
      headers: getHeaders()
    });
    
    console.log('角色列表数据:', response.data);
    
    if (response.data && response.data.code === 200 && response.data.data) {
      rolesList.value = response.data.data;
    } else if (response.data && Array.isArray(response.data)) {
      rolesList.value = response.data;
    } else {
      ElMessage.warning('获取角色列表数据格式异常');
      console.error('角色数据格式异常:', response.data);
    }
    
    console.log('处理后的角色列表:', rolesList.value);
  } catch (error) {
    console.error('获取角色列表失败:', error);
    ElMessage.error('获取角色列表失败');
  }
};

// 获取资源列表
const getResourcesList = async () => {
  try {
    const response = await axios.get(`${baseUrl}/manage/resources/`, {
      headers: getHeaders()
    });
    
    console.log('资源列表数据:', response.data);
    
    if (response.data && response.data.code === 200 && response.data.data) {
      resourcesList.value = response.data.data;
    } else if (response.data && Array.isArray(response.data)) {
      resourcesList.value = response.data;
    } else {
      // 如果API未返回数据或格式不对，使用图片中的硬编码数据
      console.log('使用硬编码资源数据:', resourcesList.value);
    }
  } catch (error) {
    console.error('获取资源列表失败:', error);
    ElMessage.error('获取资源列表失败');
    
    // 如果API请求失败，使用图片中的硬编码数据

    console.log('使用硬编码资源数据:', resourcesList.value);
  }
};

// 获取医生详情
const getDoctorDetail = async (doctorId) => {
  loading.value = true;
  try {
    const response = await axios.get(`${baseUrl}/manage/doctor-permission/${doctorId}/`, {
      headers: getHeaders()
    });
    
    console.log('医生详情数据:', response.data);
    
    let doctorData = response.data;
    
    // 检查是否数据在data字段中
    if (response.data && response.data.code === 200 && response.data.data) {
      doctorData = response.data.data;
    }
    
    // 从嵌套结构中获取医生数据
    const doctor = doctorData.doctor || doctorData;
    
    // 更新表单数据
    formData.name = doctor.name || '';
    formData.phone = doctor.phone || '';
    
    // 处理角色ID
    if (doctor.role) {
      formData.role_id = typeof doctor.role === 'object' ? doctor.role.id : doctor.role;
    } else {
      formData.role_id = '';
    }
    
    // 处理科室ID
    if (doctor.department) {
      formData.department_id = typeof doctor.department === 'object' ? doctor.department.id : doctor.department;
    } else {
      formData.department_id = '';
    }
    
    // 设置资源权限
    // 如果资源在doctorData.resources中（API返回格式）
    if (doctorData.resources && Array.isArray(doctorData.resources)) {
      formData.resources = doctorData.resources.map(resource => resource.id);
      console.log('从doctorData.resources设置权限:', formData.resources);
    }
    // 如果资源在doctor.resources中
    else if (doctor.resources && Array.isArray(doctor.resources)) {
      formData.resources = doctor.resources.map(resource => 
        typeof resource === 'object' ? resource.id : resource
      );
      console.log('从doctor.resources设置权限:', formData.resources);
    } else {
      formData.resources = [];
      console.log('没有找到资源数据，设置空数组');
    }
    
    currentDoctorId.value = doctorId;
  } catch (error) {
    console.error('获取医生详情失败:', error);
    ElMessage.error('获取医生详情失败');
  } finally {
    loading.value = false;
  }
};

// 搜索医生
const handleSearch = () => {
  // 这里可以实现本地筛选或发送搜索请求
  // 简单示例：本地筛选
  getDoctorList(); // 重新获取列表
};

// 重置搜索条件
const resetSearch = () => {
  searchForm.name = '';
  searchForm.department = '';
  getDoctorList(); // 重新获取列表
};

// 打开添加医生对话框
const handleAdd = () => {
  // 重置表单
  formData.name = '';
  formData.phone = '';
  formData.role_id = '';
  formData.department_id = '';
  formData.resources = [];
  
  isEdit.value = false;
  dialogTitle.value = '添加医生';
  dialogVisible.value = true;
  currentDoctorId.value = null;
};

// 打开编辑医生对话框
const handleEdit = (doctorId) => {
  getDoctorDetail(doctorId);
  isEdit.value = true;
  dialogTitle.value = '编辑医生';
  dialogVisible.value = true;
};

// 取消编辑
const handleCancel = () => {
  dialogVisible.value = false;
  // 重新获取医生列表，确保数据正确显示
  getDoctorList();
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return;
    
    loading.value = true;
    try {
      const data = { ...formData };
      
      // 确保resources字段是ID数组
      if (data.resources && Array.isArray(data.resources)) {
        // 如果resources中包含对象，提取ID
        if (data.resources.length > 0 && typeof data.resources[0] === 'object') {
          data.resources = data.resources.map(resource => resource.id);
        }
      }
      
      console.log('提交的表单数据:', data);
      
      if (isEdit.value) {
        // 更新医生
        await axios.put(`${baseUrl}/manage/doctor-permission/${currentDoctorId.value}/`, data, {
          headers: getHeaders()
        });
        ElMessage.success('更新成功');
      } else {
        // 添加医生
        await axios.post(`${baseUrl}/manage/doctor-permission/`, data, {
          headers: getHeaders()
        });
        ElMessage.success('添加成功');
      }
      
      dialogVisible.value = false;
      getDoctorList(); // 刷新列表
    } catch (error) {
      console.error('操作失败:', error);
      ElMessage.error('操作失败，请检查输入数据');
    } finally {
      loading.value = false;
    }
  });
};

// 删除医生
const handleDelete = (doctorId) => {
  ElMessageBox.confirm('确定要删除该医生吗？此操作不可撤销。', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    loading.value = true;
    try {
      await axios.delete(`${baseUrl}/manage/doctor-permission/${doctorId}/`, {
        headers: getHeaders()
      });
      
      ElMessage.success('删除成功');
      getDoctorList(); // 刷新列表
    } catch (error) {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    } finally {
      loading.value = false;
    }
  }).catch(() => {
    // 取消删除
  });
};

// 格式化部门名称
const formatDepartment = (departmentId) => {
  const department = departmentList.value.find(item => item.id === departmentId);
  return department ? department.name : '未知';
};

// 格式化角色名称
const formatRole = (roleId) => {
  if (!roleId) return '未分配';
  
  const role = rolesList.value.find(item => item.id === roleId);
  console.log('查找角色:', roleId, role);
  return role ? role.name : '未知';
};

// 构建资源树结构
const resourcesTree = computed(() => {
  // 先找出所有父资源（pid为null的资源）
  const parentResources = resourcesList.value.filter(item => item.pid === null);
  
  // 为每个父资源构建子资源
  return parentResources.map(parent => {
    const children = resourcesList.value.filter(item => item.pid === parent.id);
    return {
      id: parent.id,
      label: parent.name,
      children: children.map(child => ({
        id: child.id,
        label: child.name
      }))
    };
  });
});

// 页面加载时获取数据
onMounted(async () => {
  try {
    // 先获取资源列表和角色列表
    await getResourcesList();
    await getRolesList();
    
    // 然后获取医生列表
    await getDoctorList();
    
    // 调试输出
    console.log('资源树结构:', resourcesTree.value);
  } catch (error) {
    console.error('初始化数据失败:', error);
  }
});
</script>

<template>
  <div class="doctor-permission-container">
    <el-card class="search-card">
      <template #header>
        <div class="card-header">
          <span>医生权限管理</span>
          <el-button type="primary" @click="handleAdd">添加医生</el-button>
        </div>
      </template>
      
      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline>
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入医生姓名" clearable></el-input>
        </el-form-item>
        
        <el-form-item label="科室">
          <el-select v-model="searchForm.department" placeholder="请选择科室" clearable>
            <el-option 
              v-for="item in departmentList" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 医生列表 -->
    <el-card class="table-card">
      <el-table 
        :data="doctorList" 
        style="width: 100%" 
        v-loading="loading"
        border
      >
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="name" label="姓名" width="120"></el-table-column>
        <el-table-column prop="phone" label="手机号" width="140"></el-table-column>
        
        <el-table-column label="科室" width="120">
          <template #default="scope">
            <span>{{ scope.row.department_name || '未分配' }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="角色" width="120">
          <template #default="scope">
            <span>{{ scope.row.role_name || '未分配' }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="权限资源">
          <template #default="scope">
            <div v-if="scope.row.resources && scope.row.resources.length > 0" class="resource-list">
              <el-tag 
                v-for="resource in scope.row.resources" 
                :key="resource.id"
                type="info"
                class="resource-tag"
              >
                {{ resource.name }}
              </el-tag>
            </div>
            <span v-else>未分配</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="handleEdit(scope.row.id)"
            >编辑</el-button>
            
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 添加/编辑医生对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="600px"
      destroy-on-close
    >
      <el-form 
        ref="formRef"
        :model="formData" 
        :rules="rules" 
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入医生姓名"></el-input>
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        
        <el-form-item label="科室" prop="department_id">
          <el-select v-model="formData.department_id" placeholder="请选择科室" style="width: 100%">
            <el-option 
              v-for="item in departmentList" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="角色" prop="role_id">
          <el-select v-model="formData.role_id" placeholder="请选择角色" style="width: 100%">
            <el-option 
              v-for="item in rolesList" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="权限资源">
          <el-tree-select
            v-model="formData.resources"
            :data="resourcesTree"
            show-checkbox
            node-key="id"
            multiple
            default-expand-all
            :props="{
              children: 'children',
              label: 'label'
            }"
            placeholder="请选择权限资源"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="loading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.doctor-permission-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-card {
  margin-bottom: 20px;
}

.resource-list {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.resource-tag {
  margin-right: 0;
  margin-bottom: 0;
  white-space: nowrap;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 